// Copyright (c) 2009 Luca Marrocco.
// Modified or written by Luca Marrocco for inclusion with codej.
// Licensed under the Apache License, Version 2.0 (the "License")
package codej.ast.factory;

import codej.ast.*;

/** @author Luca Marrocco */
public class DefaultNodeFactory implements NodeFactory {

	public Class concreteClass(Class interfaceClass) {
		String simpleName = interfaceClass.getSimpleName();
		String packageName = interfaceClass.getPackage().getName();
		String concreteClassName = concreteClassName(packageName, "Default", simpleName);

		try {
			ClassLoader classLoader = getClass().getClassLoader();
			return classLoader.loadClass(concreteClassName);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	/** @return a concrete class name: packageName + .Default + simpleName */
	public String concreteClassName(String packageName, String concreteClassNamePrefix, String simpleName) {
		StringBuffer stringBuffer = new StringBuffer();
		stringBuffer.append(packageName);
		stringBuffer.append(".");
		stringBuffer.append(concreteClassNamePrefix);
		stringBuffer.append(simpleName);
		return stringBuffer.toString();
	}

	public Object createNode(Class aInterface) {
		return createObject(aInterface);
	}

	/**
	 * create a object class instance. If objectClass is Person.class it make a
	 * DefaultPerson instance.
	 */
	public Object createObject(Class interfaceClass) {
		Class concreteClass = null;

		try {
			concreteClass = concreteClass(interfaceClass);

			return (Object) concreteClass.newInstance();
		} catch (Exception e) {
			throw new RuntimeException("unable to make new instance for class " + concreteClass + " and interface " + interfaceClass);
		}
	}
}